﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using MFTool;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace MF_Base
{
    public class ControlFieldTypeC
    {
        /// <summary>
        /// 模型字段类型与数据库字段数据类型的映射
        /// </summary>
        /// <param name="propertyTypeString"></param>
        /// <returns></returns>
        public static string PropertyTypeStringToControlFieldType(PropertyInfo propertyInfo)
        {
            string propertyTypeString = propertyInfo.PropertyType.ToString();
            if (propertyTypeString.Contains("System.Int32"))
            {
                return SqlServerDataType.INT.ToDescription();
            }
            else if (propertyTypeString.Contains("System.String"))
            {
                var res = SqlServerDataType.NVARCHAR_MAX_.ToDescription();
                var v = (MaxLengthAttribute[])propertyInfo.GetCustomAttributes(typeof(MaxLengthAttribute), false);
                if (v != null && v.Count() > 0)
                {
                    res = res.Replace("max", v[0].Length.ToString());
                }
                else
                {
                    var v1 = (ForeignKeyAttribute[])propertyInfo.GetCustomAttributes(typeof(ForeignKeyAttribute), false);
                    if (v1 != null && v1.Count() > 0)
                    {
                        res = res.Replace("max", "50");
                    }
                }

                return res;
            }
            else if (propertyTypeString.Contains("System.DateTime"))
            {
                return SqlServerDataType.DATETIME.ToDescription();
            }
            else if (propertyTypeString.Contains("System.Decimal"))
            {
                return SqlServerDataType.FLOAT.ToDescription();
            }
            else if (propertyTypeString.Contains("System.Double"))
            {
                return SqlServerDataType.FLOAT.ToDescription();
            }
            else if (propertyTypeString.Contains("System.Boolean"))
            {
                return SqlServerDataType.BIT.ToDescription();
            }
            else if (propertyTypeString.Contains("Collection"))
            {
                return SqlServerDataType.LIST.ToDescription();
            }

            return propertyTypeString;
        }
    }    

    public enum SqlServerDataType
    {
        [Description("nvarchar(max)")]
        NVARCHAR_MAX_ = 1,
        [Description("int")]
        INT,
        [Description("float")]
        FLOAT,
        [Description("double")]
        DOUBLE,
        [Description("datetime")]
        DATETIME,
        [Description("bit")]
        BIT,
        [Description("nvarchar(max)")]
        LIST,
    }

}
